from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
import json

# Create your views here.
from apps.home.filters import EmployeeFilter
from apps.home.models import AppList, Employee
from apps.home.serializer import AppListSerializer, EmployeeSerializer
# from apps.knowledge_graph.models import Triple

from django.contrib.auth.models import User
from apps.home.serializer import UserSerializer

from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend

# from import_module.config_file_import import import_database


class AppListViewSet(viewsets.ModelViewSet):
    queryset = AppList.objects.all()
    serializer_class = AppListSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['app_name', 'app_type', 'app_config', 'app_role']

    # @action(methods=['get'], detail=False)
    # def config(self, request):
    #     try:
    #         with open('config_file/config_2.json') as config_file:
    #
    #     except Exception as e:
    #         return Response(e)

    # @action(methods=['get'], detail=False)
    # def load_config(self, request):
    #     import_database(json_path='config_file/config.json', tables_list=[], import_all=True)
    #     return Response("success!!")
    #
    # @action(methods=['get'], detail=False)
    # def load_knowledge_graph(self, request):
    #     Triple.objects.all().delete()
    #     try:
    #         with open('config_file/knowledge_graph_triple.json', encoding='UTF-8') as config_file:
    #             config = json.load(config_file)
    #             triple_data = config['RECORDS']
    #             triple_list = []
    #             for triple in triple_data:
    #                 triple_instance = Triple()
    #                 triple_instance.id = triple["id"]
    #                 triple_instance.subject = triple["subject"]
    #                 triple_instance.predicate = triple["predicate"]
    #                 triple_instance.object = triple["object"]
    #                 triple_list.append(triple_instance)
    #             Triple.objects.bulk_create(triple_list)
                # return Response(app_data)
                # return Response("success!!")
        # except Exception as e:
        #     e = 0
        #     return Response(e)

    @action(methods=['get'], detail=False)
    def load_app(self, request):
        AppList.objects.all().delete()
        try:
            with open('config_file/app_config.json', encoding='UTF-8') as config_file:
                config = json.load(config_file)
                app_data = config['appList']
                app_list = []
                for app in app_data:
                    app_instance = AppList()
                    app_instance.id = app["id"]
                    app_instance.app_name = app["app_name"]
                    app_instance.app_type = app["app_type"]
                    app_instance.app_config = app["app_config"]
                    app_instance.app_icon = app["app_icon"]
                    app_instance.app_href = app["app_href"]
                    app_instance.app_role = "管理员"
                    app_list.append(app_instance)
                AppList.objects.bulk_create(app_list)
                return Response(app_data)
                # return Response("success!!")
        except Exception as e:
            # e = 0
            return Response(e)

    @action(methods=['get'], detail=False)
    def config_privilege(self, request):
        try:
            with open('config_file/privilege.json', encoding='UTF-8') as privilege_file:
                privilege = json.load(privilege_file)
                privilege_list = []
                step = 100
                for key in privilege:
                    print(key)
                    print(privilege[key])
                    for i in privilege[key]:
                        print(i)
                        app = AppList.objects.get(app_name=i, app_role="管理员")
                        print(app)
                        app.id = app.id + step
                        app.app_role = key
                        privilege_list.append(app)
                    step += 100
                AppList.objects.bulk_create(privilege_list)
            return Response("success!!")
        except Exception as e:
            e = 0
            return Response(e)


class EmployeeViewSet(viewsets.ModelViewSet):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
    filter_backends = [DjangoFilterBackend]
    filter_class = EmployeeFilter


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['username', 'first_name']

    # 新建用户
    @action(methods=['post'], detail=False)
    def add_user(self, request):
        try:
            job_number = request.data['jobNumber']
            name = request.data['name']
            phone = request.data['phone']
            department = request.data['department']
            role = request.data['role']
            password = request.data['password']
            user = User.objects.create_superuser(username=job_number, password=password)
            user.first_name = name
            user.save()
            employee = Employee()
            employee.job_number = job_number
            employee.name = name
            employee.phone = phone
            employee.department = department
            employee.role = role
            employee.user = user
            employee.save()
            return Response('success!!')
        except Exception as e:
            e = 0
            return Response(e)

    # 编辑用户
    @action(methods=['post'], detail=False)
    def edit_user(self, request):
        try:
            job_number = request.data['jobNumber']
            department = request.data['department']
            role = request.data['role']
            user = User.objects.get(username=job_number)
            employee = Employee.objects.get(user=user)
            employee.department = department
            employee.role = role
            employee.save()
            return Response('success!!')
        except Exception as e:
            e = 0
            return Response(e)

    # 删除用户
    @action(methods=['post'], detail=False)
    def delete_user(self, request):
        try:
            job_number = request.data['jobNumber']
            user = User.objects.get(username=job_number)
            user.delete()
            return Response('success!!')
        except Exception as e:
            e = 0
            return Response(e)

    # 修改密码
    @action(methods=['post'], detail=False)
    def change_password(self, request):
        try:
            job_number = request.data['jobNumber']
            password = request.data['password']
            user = User.objects.get(username=job_number)
            user.set_password(password)
            user.save()
            return Response('success!!')
        except Exception as e:
            e = 0
            return Response(e)
